from rest_framework.throttling import BaseThrottle,SimpleRateThrottle
import time

VISIT_RECORD = {}   # 可以用缓存代替

# 用写好的组件
class MyThrottle(SimpleRateThrottle):
    scop = "JACK"
    def get_cache_key(self, request, view):
        return self.get_ident(request)

# 自己实现
class VisitThrottle(BaseThrottle):
    def __init__(self):
        self.history = None
    def allow_request(self, request, view):
        """Return
        `True` 可以访问,
        `False` 不能访问.
        """
        # 获取用户ip
        remote_addr = request.META.get('REMOTE_ADDR')
        ctime = time.time()
        if remote_addr not in VISIT_RECORD:
            VISIT_RECORD[remote_addr] = ctime
            return True
        history = VISIT_RECORD.get(remote_addr)
        self.history = history
        while history and history[-1] < ctime - 60:
            history.pop()
        if len(history) < 3:
            history.insert(0, remote_addr)
            return True
        return False

    def wait(self):
        """再等多少秒访问"""
        ctime = time.time()
        return 60 - (ctime - self.history[-1])
